<template>
  <div class="app-container home">
    <!-- 搜索区域 - 保持与知识点管理相同 -->
    <el-form :model="searchForm" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="试卷名称">
            <el-input v-model="searchForm.name" placeholder="请输入试卷名称" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="年级">
            <el-select 
              v-model="searchForm.grades" 
              multiple 
              placeholder="请选择年级"
              style="width: 100px"
            >
              <el-option
                v-for="grade in gradeOptions"
                :key="grade"
                :label="grade"
                :value="grade"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="地区">
            <el-cascader
              v-model="searchForm.area"
              :options="areaOptions"
              placeholder="请选择地区"
              style="width: 100%"
              :props="{ expandTrigger: 'hover' }"
            />
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="科目">
            <el-select 
              v-model="searchForm.subject" 
              placeholder="请选择科目"
              style="width: 100%"
            >
              <el-option label="数学" value="数学" />
              <el-option label="英语" value="英语" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="20">
          <el-button type="primary" @click="add">新增试卷</el-button>
        </el-col>
        <el-col :span="2">
          <div class="search-actions">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格区域 - 修改为试卷管理字段 -->
    <el-table
      ref="tableRef"
      :data="tableData"
      border
      stripe
      :row-key="row => row.id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="试卷名称" min-width="180">
        <template #default="scope">
          <el-link 
            type="primary"
            @click="handleDetail(scope.row)"
          >
            {{ scope.row.name }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="area" label="省-市" width="120" />
      <el-table-column prop="grades" label="年级" min-width="150">
        <template #default="scope">
          <el-tag v-for="grade in scope.row.grades" :key="grade">{{ grade }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="subject" label="科目" width="100" />
      <el-table-column label="操作" width="260" fixed="right">
        <template #default="scope">
          <el-button type="text" size="small" @click="handlePreview(scope.row)">预览</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      class="pagination"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      layout="prev, pager, next, jumper"
    />

    <!-- 新增批量操作栏 -->
    <div v-if="selectedRows.length > 0" class="batch-actions">
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      <el-button @click="handleCancelSelection">取消勾选</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router'  // 新增路由导入
const router = useRouter()  // 初始化路由实例
// 搜索表单 - 适配试卷管理字段
const searchForm = reactive({
  name: '',
  grades: [],
  area: ['安徽', '合肥'],
  subject: ''
})

// 年级选项
const gradeOptions = ['初一', '初二', '初三', '高一', '高二', '高三']

// 地区选项
const areaOptions = ref([{
  value: '安徽',
  label: '安徽',
  children: [{
    value: '合肥',
    label: '合肥'
  }, {
    value: '芜湖',
    label: '芜湖'
  }]
}, {
  value: '江苏',
  label: '江苏',
  children: [{
    value: '南京',
    label: '南京'
  }, {
    value: '苏州',
    label: '苏州'
  }]
}])

// 表格数据 - 模拟试卷数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])

// 模拟试卷数据
let mockData = Array.from({ length: 50 }, (_, i) => ({
  id: i + 1,
  name: `试卷${i + 1}`,
  grades: gradeOptions.slice(0, Math.ceil(Math.random() * 2)),
  subject: ['数学', '英语' ][Math.floor(Math.random() * 2)],
  area: `${['安徽', '江苏'][Math.floor(Math.random() * 2)]}-${['合肥', '芜湖', '南京', '苏州'][Math.floor(Math.random() * 4)]}`
}))

// 搜索方法 - 适配试卷字段过滤
const handleSearch = () => {
  const filtered = mockData.filter(item => {
    return item.name.includes(searchForm.name) &&
      (searchForm.grades.length ? searchForm.grades.some(g => item.grades.includes(g)) : true) &&
      (searchForm.subject ? item.subject === searchForm.subject : true) &&
      (searchForm.area.length ? item.area.includes(searchForm.area.join('-')) : true)
  })

  total.value = filtered.length
  tableData.value = filtered.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
}

// 重置方法
const handleReset = () => {
  searchForm.name = ''
  searchForm.grades = []
  searchForm.area = ['安徽', '合肥']
  searchForm.subject = ''
  currentPage.value = 1
  handleSearch()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  handleSearch()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  handleSearch()
}

// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 编辑处理
const handleEdit = (row) => {
  // 实际项目中这里应该跳转到编辑页面
  router.push({ path: '/testPapers/add', query: { id: row.id } })
}

const handlePreview = (row) => {
  // 实际项目中这里应该跳转到预览页面
  router.push({ path: '/testPapers/testPaperRender', query: { id: row.id } })
}

// 删除处理
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该试卷吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    mockData = mockData.filter(item => item.id !== id)
    handleSearch()
    ElMessage({ message: '删除成功', type: 'success' })
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return
  ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条试卷吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.id)
    mockData = mockData.filter(item => !ids.includes(item.id))
    selectedRows.value = []
    handleSearch()
    ElMessage({ message: '批量删除成功', type: 'success' })
  }).catch(() => {})
}

import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()

// 取消勾选
const handleCancelSelection = () => {
  selectedRows.value = []
  proxy.$refs.tableRef.clearSelection()
}

// 详情处理
const handleDetail = (row) => {
  ElMessage({ message: `查看试卷详情: ${row.name}`, type: 'info' })
  // 实际项目中这里应该跳转到详情页面
}

// 初始化加载数据
handleSearch()

// 新增试卷
function add () {
  router.push({ path: '/testPapers/add' })
}
</script>

<style scoped>
/* 保持与知识点管理页面相同的样式 */
.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.search-actions {
  display: flex;
  gap: 10px;
  margin-top: 22px;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

.batch-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}
</style>